<?php

namespace app\index\controller;

use app\index\job\DelayTask;
use DOMDocument;
use Ramsey\Uuid\Guid\Guid;
use think\Cache;
use think\Controller;
use think\Db;
use think\Loader;
use think\Queue;
use think\Request;
use think\Validate;
use wxsdk\wxPay;

class Api extends Controller
{
    public function openidToUserid()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';

        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;

        $user_data = json_decode(httpsRequest($url));
        if ($user_data->errcode) apiReturn(2, '系统繁忙，请稍后再试~' . $user_data->errcode);

        $openid = $user_data->openid;

        if (empty($openid)) apiReturn(2, '登录失败');

        $user_info = Db::name('user')->field('id,is_auth')->where(['openid' => $openid])->find();

        if ($user_info) {
            apiReturn(1, '登录成功', $user_info);
        } else {
            apiReturn(2, '新用户，走注册流程');
        }
    }

    /**
     * 获取openid
     */
    public function getOpenid()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code)) apiReturn(2, '系统繁忙，请稍后再试~');

        $appid = C('XCX_APPID');
        $secret = C('XCX_SECRET');
        $grant_type = 'authorization_code';
        $url = 'https://api.weixin.qq.com/sns/jscode2session?';

        $param = [
            'appid' => $appid,
            'secret' => $secret,
            'js_code' => $code,
            'grant_type' => $grant_type
        ];
        $param_str = http_build_query($param);
        $url .= $param_str;
        $json_res = httpsRequest($url);
        $user_data = json_decode($json_res);

        if ($openid = $user_data->openid) {
            apiReturn(1, '获取数据成功', $openid);
        } else {
            apiReturn(2, '系统繁忙，请稍后再试~');
        }
    }

    /**
     * 获取手机号
     * */
    public function getMobile()
    {
        $input = Request()->param();

        $code = $input['code'];

        if (empty($code) || $code == 'undefined') apiReturn(2, 'code缺失');

        $token = get_access_token('xcx_access_token.json', 2);
        if (empty($token)) apiReturn(2, 'TOKEN缺失');

        $url = 'https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=' . $token . '&code=' . $code;

        $data = [
            'code' => $code
        ];
        $result = httpsRequest($url, json_encode($data));
        $result = json_decode($result, true);

        if ($result['errcode'] == 0) {
            $mobile = $result['phone_info']['phoneNumber'];

            if ($mobile) {
                apiReturn(1, '获取数据成功', $mobile);
            } else {
                apiReturn(2, '系统繁忙，请稍后再试');
            }
        } else {
            if ($result['errcode'] == 40001) {
                apiReturn(2, '系统繁忙，请重新获取手机号');
            } elseif ($result['errcode'] == 40029) {
                apiReturn(3, '获取手机号失败，请前往【我 => 设置 => 关于微信】将微信版本更新至不低于8.0.16后，再回到此界面点击绑定手机');
            } else {
                apiReturn(2, '系统繁忙，请稍后再试~');
            }
        }
    }


    /**
     * 登录
     * */
    public function login()
    {
        $input = Request()->param();

        $openid = $input['openid'];
        $avatar = $input['avatar'];
        $nickname = $input['nickname'];
        $mobile = $input['mobile'];
        $share_user_id = $input['share_user_id'] ? : 0;

        if (empty($openid)) apiReturn(2, 'openid缺失');
//        if (empty($avatar)) apiReturn(2, '请上传头像信息');
//        if (empty($nickname)) apiReturn(2, '请填写昵称');
        if (empty($mobile)) apiReturn(2, '请获取手机号');

        $mobile_count = Db::name('user')->where(['mobile' => $mobile])->count();
        if ($mobile_count > 0) apiReturn(2, '该手机号已使用');

        Db::startTrans();
        try {
            $count = Db::name('user')->where(['openid' => $openid])->count();
            if ($count) {
                $user_id = Db::name('user')->where(['openid' => $openid])->value('id');
            } else {
                $data = [
                    'openid' => $openid,
//                    'avatar' => str_replace(getHost(), '', $avatar),
//                    'nickname' => $nickname,
                    'mobile' => $mobile,
                    'user_code' => getUserCode(),
                    'up_user_id' => $share_user_id,
                    'create_time' => time()
                ];

                $user_id = Db::name('user')->insertGetId($data);
            }

            Db::commit();
            apiReturn(1, '登录成功', $user_id);
        } catch (\Exception $e) {
            Db::rollback();
            apiReturn(2, '系统繁忙，请稍后再试~' . $e->getMessage());
        }
    }

    /**
     * 检测是否首次提交
     * */
    public function checkFirstSubmitInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $type = $input['type'] ? : 1;// 1：工资人员信息，2：工资薪金所得，3：当月开票申请，4：企业所得税抵扣

        if (empty($user_id)) apiReturn(3, '用户ID缺失');

        switch ($type) {
            case 2:
                $table = 'salary';
                break;
            case 3:
                $table = 'invoice';
                break;
            case 4:
                $table = 'tax_deduction_user';
                break;
            default:
                $table = 'staff';
                break;
        }

        $count = Db::name($table)->where(['user_id' => $user_id])->count();

        $data = [
            'tip_text' => C('TIP_TEXT'),
            'count' => $count
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 获取首页数据
     * */
    public function getIndexData()
    {
        $input = Request()->param();

        $user_id = isset($input['user_id']) ? $input['user_id'] : 0;

        // 未读数量
        if (!$user_id) {
            $no_read_count = 0;
        } else {
            $no_read_count = Db::name('msg m')
                ->join('tp_msg_read r', 'm.id = r.msg_id AND r.user_id = ' . $user_id, 'left')
                ->where(function ($query) use ($user_id) {
                    $query->where('m.user_id', 0)
                        ->whereOr('m.user_id', $user_id);
                })
                ->whereNull('r.id')
                ->count();
        }

        $banner_list = Db::name('banner')->field('id,img')->order('id desc')->select();
        if ($banner_list) {
            foreach ($banner_list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
        }

        $service_list = Db::name('service')->field('id,img,name,des')->where(['is_recommend' => 1, 'is_upper' => 1])->order('sort asc,id desc')->limit(2)->select();
        foreach ($service_list as &$v) {
            $v['img'] = getPicture($v['img']);
        }

        $is_auth = Db::name('user')->where(['id' => $user_id])->value('is_auth');

        $data = [
            'no_read_count' => $no_read_count,
            'banner_list' => $banner_list ? : [],
            'service_list' => $service_list ? : [],
            'is_auth' => $is_auth
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 服务列表
     * */
    public function serviceList()
    {
        $input = Request()->param();

        $page = isset($input['page']) ? $input['page'] : 1;
        $pagesize = isset($input['pagesize']) ? $input['pagesize'] : 10;

        $where['is_upper'] = 1;
        $where['is_del'] = 0;

        $list = Db::name('service')->field('id,img,name,des')->where($where)->order('sort asc,is_recommend desc, id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['img'] = getPicture($v['img']);
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 服务详情
     * */
    public function serviceDetail()
    {
        $input = Request()->param();

        $id = $input['id'];

        if (!$id) apiReturn(2, '参数错误');

        $info = Db::name('service')->field('id,name,price,days,content,know')->where('is_del', 0)->where('id', $id)->find();
        if ($info) {
            $info['content'] = doEditorContent($info['content']);
            $info['know'] = doEditorContent($info['know']);


            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(2, '服务不存在');
        }
    }

    /**
     * 通知列表
     * */
    public function msgList()
    {
        $input = Request()->param();

        $user_id = isset($input['user_id']) ? $input['user_id'] : 0;
        $page = isset($input['page']) ? $input['page'] : 1;
        $pagesize = isset($input['pagesize']) ? $input['pagesize'] : 10;

        $list = Db::name('msg')->field('id,type,content,create_time')->whereIn('user_id', [0, $user_id])->page($page, $pagesize)->order('id desc')->select();
        if ($list) {

            $read_data = [];
            $time = time();
            foreach ($list as &$v) {
                $v['create_time'] = formatMsgTime($v['create_time']);

                $count = Db::name('msg_read')->where(['msg_id' => $v['id'], 'user_id' => $user_id])->count();
                if ($count == 0) {
                    $read_data[] = [
                        'msg_id' => $v['id'],
                        'user_id' => $user_id,
                        'create_time' => $time
                    ];
                }
            }
            if ($read_data) Db::name('msg_read')->insertAll($read_data);

            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 我的推广
     * */
    public function mySpread()
    {
        $input = Request()->param();

        $user_id = isset($input['user_id']) ? $input['user_id'] : 0;
        $page = isset($input['page']) ? $input['page'] : 1;
        $pagesize = isset($input['pagesize']) ? $input['pagesize'] : 10;

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');

        $profit = Db::name('user')->where('id', $user_id)->value('profit');

        $count = Db::name('user')->where('up_user_id', $user_id)->count();

        $list = Db::name('user')->field('id,avatar,user_code,nickname,company_name,create_time')->where('up_user_id', $user_id)->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['avatar'] = getPicture($v['avatar']);
                $v['create_time'] = timeFormat($v['create_time'], 'Y年m月d日');
            }
        } else {
            $list = [];
        }

        $data = [
            'profit' => $profit,
            'count' => $count,
            'list' => $list
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 收益明细
     * */
    public function profitList()
    {
        $input = Request()->param();

        $user_id = isset($input['user_id']) ? $input['user_id'] : 0;
        $page = isset($input['page']) ? $input['page'] : 1;
        $pagesize = isset($input['pagesize']) ? $input['pagesize'] : 10;

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');

        $list = Db::name('profit_log')->field('id,profit,before,after,remark,create_time')->where('user_id', $user_id)->page($page, $pagesize)->order('id desc')->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['create_time'] = timeFormat($v['create_time'], 'Y年m月d日');
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 用户信息
     * */
    public function userCenter()
    {
        $input = Request()->param();

        $user_id = isset($input['user_id']) ? $input['user_id'] : 0;

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');

        $info = Db::name('user')->field('id,avatar,nickname,mobile,is_auth')->where('id', $user_id)->find();
        if ($info) {
            $info['avatar'] = getPicture($info['avatar']);
            $info['hide_mobile'] = hideMobile($info['mobile']);
            $info['work_time'] = array_filter(C('WORK_TIME'));

            apiReturn(1, '获取数据成功', $info);
        } else {
            apiReturn(3, '未查询到账户信息');
        }
    }

    /**
     * 获取员工信息列表
     * */
    public function staffList()
    {
        $input = Request()->param();

        $user_id = isset($input['user_id']) ? $input['user_id'] : 0;

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');

        $list = Db::name('staff')->field('user_id,username,id_type,id_num,mobile,is_deduct_fee,is_disabled,is_widow,is_lonely')->where('user_id', $user_id)->order('id asc')->select();

        apiReturn(1, '获取数据成功', $list);
    }

    /**
     * 保存员工信息
     * */
    public function saveStaff()
    {
        $input = Request()->param();

        $user_id = isset($input['user_id']) ? $input['user_id'] : 0;
        $list = isset($input['list']) ? $input['list'] : [];

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');

        if ($list) {
            Db::startTrans();
            try {
                $count = Db::name('staff')->where('user_id', $user_id)->count();
                if ($count) {
                    $res = Db::name('staff')->where('user_id', $user_id)->delete();
                    if (!$res) {
                        Db::rollback();
                        apiReturn(2, '更新失败');
                    }
                }

                $company_id = Db::name('company')->where('user_id', $user_id)->value('id');

                $time = time();
                foreach ($list as &$v) {
                    if (!$v['username'] || $v['id_type'] == '' || !$v['id_num'] || !$v['mobile']) {
                        apiReturn(2, '请完善所有工资人员信息');
                        break;
                    }

                    $v['company_id'] = $company_id ? : 0;
                    $v['create_time'] = $time;
                }

                $res = Db::name('staff')->insertAll($list);
                if ($res) {
                    Db::commit();
                    apiReturn(1, '更新成功');
                } else {
                    Db::rollback();
                    apiReturn(2, '更新失败');
                }
            } catch (\Throwable $e) {
                Db::rollback();
                apiReturn(2, '更新失败');
            }
        }
    }

    /**
     * 删除员工
     * */
    public function delStaff()
    {
        $input = Request()->param();

        $id = isset($input['id']) ? $input['id'] : 0;

        if (!$id) apiReturn(3, '参数错误');

        $res = Db::name('staff')->where('id', $id)->delete();
        if ($res) {
            apiReturn(1, '删除成功');
        } else {
            apiReturn(2, '删除失败');
        }
    }

    public function getStaffList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (empty($user_id)) apiReturn(2, '您还未登录，请先登录');

        $list = Db::name('staff')->field('id,username,id_num')->where('user_id', $user_id)->select();

        apiReturn(1, '获取数据成功', $list);
    }

    /**
     * 保存工资薪资所得税
     * */
    public function saveSalary()
    {
        $input = Request()->param();

        $user_id = isset($input['user_id']) ? $input['user_id'] : 0;
        $list = isset($input['list']) ? $input['list'] : [];

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');

        if ($list) {
            $company_id = Db::name('company')->where('user_id', $user_id)->value('id');

            Db::startTrans();
            try {
                $time = time();
                $quarter = getQuarter();
                foreach ($list as &$v) {
                    unset($v['show_tip_model']);
                    if (!$v['username'] || $v['id_type'] == '' || !$v['id_num'] || !$v['income_period_start'] || !$v['income_period_end'] || !$v['current_income']) {
                        apiReturn(2, '请完善所有工资薪资所得税信息');
                        break;
                    }

                    $v['company_id'] = $company_id ? : 0;
                    $v['year'] = date('Y');
                    $v['month'] = date('m');
                    $v['quarter'] = $quarter;
                    $v['create_time'] = $time;
                }

                $res = Db::name('salary')->insertAll($list);
                if ($res) {
                    Db::commit();
                    apiReturn(1, '更新成功');
                } else {
                    Db::rollback();
                    apiReturn(2, '更新失败');
                }
            } catch (\Throwable $e) {
                Db::rollback();
                apiReturn(2, '更新失败');
            }
        }
    }

    /**
     * 获取所有存在的年份和季度列表
     */
    public function getYearQuarterList()
    {
        $input = Request()->param();

        $user_id = isset($input['user_id']) ? $input['user_id'] : 0;

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');

        $list = Db::name('salary')
            ->field('year, quarter')
            ->where('user_id', $user_id)
            ->group('year, quarter')
            ->order('year desc, quarter desc')
            ->select();

        foreach ($list as &$item) {
            $item['desc'] = $item['year'] . '年第' . $item['quarter'] . '季度';
        }

        apiReturn(1, '获取数据成功', $list);
    }

    /**
     * 查询记录的月份列表
     */
    public function getMonthsByUserYearQuarter()
    {
        $user_id = input('user_id/d', 0);
        $year = input('year/d', 0);
        $quarter = input('quarter/d', 0);

        if (!$user_id || !$year || !$quarter) {
            return json(['code' => 0, 'msg' => '参数缺失']);
        }

        // 查询符合条件的月份
        $months = Db::name('salary')
            ->field('month')
            ->where('user_id', $user_id)
            ->where('year', $year)
            ->where('quarter', $quarter)
            ->group('month')
            ->order('month asc')
            ->select();
        if ($months) {
            foreach ($months as &$v) {
                $v['year'] = $year;
                $v['desc'] = $year . '年' . $v['month'] . '月 工资薪金所得表填报记录';
            }
        }

        apiReturn(1, '获取数据成功', $months);
    }

    /**
     * 工资薪资所得税列表
     * */
    public function salaryList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $year = $input['year'];
        $month = $input['month'];
        $page = isset($input['page']) ? $input['page'] : 1;
        $pagesize = isset($input['pagesize']) ? $input['pagesize'] : 10;

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');
        if (!$year || !$month) apiReturn(2, '参数错误');

        $where['user_id'] = $user_id;
        $where['year'] = $year;
        $where['month'] = $month;

        $list = Db::name('salary')->where($where)->order('id asc')->page($page, $pagesize)->select();
        if ($list) {
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 开票
     * */
    public function applyInvoice()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $seller_name = $input['seller_name'];
        $invoice_type = $input['invoice_type'];
        $buyer_name = $input['buyer_name'];
        $buyer_tax_no = $input['buyer_tax_no'];
        $buyer_address_phone = $input['buyer_address_phone'];
        $buyer_bank_name = $input['buyer_bank_name'];
        $buyer_bank_account = $input['buyer_bank_account'];
        $invoice_item_name = $input['invoice_item_name'];
        $price = $input['price'];
        $tax_rate = $input['tax_rate'];

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');
        if (!$seller_name) apiReturn(2, '请填写销售单位名称');
        if (!$buyer_name) apiReturn(2, '请填写购买方单位名称');
        if (!$buyer_tax_no) apiReturn(2, '请填写购买方税号');
        if ($invoice_type == 2 && !$buyer_address_phone) apiReturn(2, '请填写购买方地址、电话');
        if ($invoice_type == 2 && !$buyer_bank_name) apiReturn(2, '请填写购买方开户行名称');
        if ($invoice_type == 2 && !$buyer_bank_account) apiReturn(2, '请填写购买方开户行账号');
        if (!$invoice_item_name) apiReturn(2, '请填写开票项目名称');
        if (!$price) apiReturn(2, '请填写金额');

        $company_id = Db::name('company')->where('user_id', $user_id)->value('id');

        $data = [
            'user_id' => $user_id,
            'company_id' => $company_id ? : 0,
            'seller_name' => $seller_name,
            'invoice_type' => $invoice_type,
            'buyer_name' => $buyer_name,
            'buyer_tax_no' => $buyer_tax_no,
            'buyer_address_phone' => $buyer_address_phone,
            'buyer_bank_name' => $buyer_bank_name,
            'buyer_bank_account' => $buyer_bank_account,
            'invoice_item_name' => $invoice_item_name,
            'price' => $price,
            'tax_rate' => $tax_rate,
            'year' => date('Y'),
            'month' => date('m'),
            'quarter' => getQuarter(),
            'create_time' => time(),
        ];

        $res = Db::name('invoice')->insert($data);
        if ($res) {
            apiReturn(1, '申请成功');
        } else {
            apiReturn(2, '申请失败');
        }
    }


    /**
     * 获取所有存在的年份和季度列表
     */
    public function getYearInvoiceList()
    {
        $input = Request()->param();

        $user_id = isset($input['user_id']) ? $input['user_id'] : 0;

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');

        $list = Db::name('invoice')
            ->field('year, quarter')
            ->where('user_id', $user_id)
            ->group('year, quarter')
            ->order('year desc, quarter desc')
            ->select();

        foreach ($list as &$item) {
            $item['desc'] = $item['year'] . '年第' . $item['quarter'] . '季度';
        }

        apiReturn(1, '获取数据成功', $list);
    }

    /**
     * 开票记录
     * */
    public function invoiceList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $year = $input['year'];
        $quarter = $input['quarter'];
        $page = isset($input['page']) ? $input['page'] : 1;
        $pagesize = isset($input['pagesize']) ? $input['pagesize'] : 10;

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');
        if (!$year || !$quarter) apiReturn(2, '缺少参数');

        $where['user_id'] = $user_id;
        $where['year'] = $year;
        $where['quarter'] = $quarter;

        $list = Db::name('invoice')->where($where)->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                $v['file_path'] = $v['file_path'] ? getHost() . $v['file_path'] : '';
                $v['create_time'] = timeFormat($v['create_time'], 'Y年m月d日');
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 税抵扣项分类-抵扣项
     * */
    public function taxDeductionLinkItem()
    {
        $list = Db::name('tax_deduction_type')->field('id,name')->where('pid', 0)->select();
        if ($list) {
            foreach ($list as &$v) {
                $child = Db::name('tax_deduction_type')->field('id,name')->where('pid', $v['id'])->select();
                if ($child) {
                    foreach ($child as &$val) {
                        $item_list = Db::name('tax_deduction_item')->field('id,title,desc')->where('two_type_id', $val['id'])->select();
                        $val['child'] = $item_list;
                    }
                }
                $v['child'] = $child;
            }
        }
        apiReturn(1, '获取数据成功', $list);
    }

    /**
     * 保存企业所得税
     * */
    public function saveTaxDeduction()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $list = $input['list'];

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');
        if (!$list) apiReturn(2, '缺少参数');

        $sn = md5(uniqid() . time());
        $year = date('Y');
        $month = date('m');
        $quarter = getQuarter();

        $company_id = Db::name('company')->where('user_id', $user_id)->value('id');

        foreach ($list as $k => &$v) {
            $v['user_id'] = $user_id;
            $v['company_id'] = $company_id ? : 0;
            $v['sn'] = $sn;
            $v['year'] = $year;
            $v['month'] = $month;
            $v['quarter'] = $quarter;
            $v['create_time'] = time();

            if (!$v['price_text'] || $v['count'] == 0 || $v['all_price'] == 0) unset($list[$k]);
        }

        if ($list) {
            $res = Db::name('tax_deduction_user')->insertAll($list);
            if ($res) {
                apiReturn(1, '提交成功');
            } else {
                apiReturn(2, '提交失败');
            }
        } else {
            apiReturn(2, '提交失败');
        }
    }


    /**
     * 获取所有存在的年份和季度列表
     */
    public function getYearTaxList()
    {
        $input = Request()->param();

        $user_id = isset($input['user_id']) ? $input['user_id'] : 0;

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');

        $list = Db::name('tax_deduction_user')
            ->field('year, quarter')
            ->where('user_id', $user_id)
            ->group('year, quarter')
            ->order('year desc, quarter desc')
            ->select();

        foreach ($list as &$item) {
            $item['desc'] = $item['year'] . '年第' . $item['quarter'] . '季度';
        }

        apiReturn(1, '获取数据成功', $list);
    }


    /**
     * 查询记录的月份列表
     */
    public function getTaxMonthsByUserYearQuarter()
    {
        $user_id = input('user_id/d', 0);
        $year = input('year/d', 0);
        $quarter = input('quarter/d', 0);

        if (!$user_id || !$year || !$quarter) {
            return json(['code' => 0, 'msg' => '参数缺失']);
        }

        // 查询符合条件的月份
        $months = Db::name('tax_deduction_user')
            ->field('month')
            ->where('user_id', $user_id)
            ->where('year', $year)
            ->where('quarter', $quarter)
            ->group('month')
            ->order('month asc')
            ->select();
        if ($months) {
            foreach ($months as &$v) {
                $v['year'] = $year;
                $v['desc'] = $year . '年' . $v['month'] . '月 工资薪金所得表填报记录';
            }
        }

        apiReturn(1, '获取数据成功', $months);
    }

    /**
     * 企业所得税历史记录
     * */
    public function taxDeductionHistory()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $year = $input['year'];
        $month = $input['month'];
        $page = isset($input['page']) ? $input['page'] : 1;
        $pagesize = isset($input['pagesize']) ? $input['pagesize'] : 10;

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');
        if (!$year || !$month) apiReturn(2, '参数错误');

        $where['user_id'] = $user_id;
        $where['year'] = $year;
        $where['month'] = $month;

        // 第一步：先查分页的 sn 分组
        $list = Db::name('tax_deduction_user')
            ->field('sn')
            ->group('sn')
            ->where($where)
            ->page($page, $pagesize)
            ->select();

        if ($list) {
            // 取出 sn 集合
            $snValues = array_column((array)$list, 'sn');

            // 第二步：再查这些 sn 下的所有明细数据
            $items = Db::name('tax_deduction_user')
                ->whereIn('sn', $snValues)
                ->order('id asc')
                ->select();

            // 第三步：按 type_name 分组
            $data = [];
            foreach ($items as &$item) {
                $item['create_time'] = timeFormat($item['create_time'], 'Y年m月d日');
                $data[$item['type_name']][] = $item;
            }

            apiReturn(1, '获取数据成功', $data);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

    /**
     * 企业认证
     * */
    public function companyAuth()
    {
        $input = Request()->param();

        $id = isset($input['id']) ? $input['id'] : 0;
        $user_id = $input['user_id'];
        $company_name = $input['company_name'];
        $company_id_type = $input['company_id_type'];
        $company_id_num = $input['company_id_num'];
        $company_img = $input['company_img'];
        $user_name = $input['user_name'];
        $user_id_type = $input['user_id_type'];
        $user_id_num = $input['user_id_num'];
        $user_mobile = $input['user_mobile'];

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');
        if (!$company_name) apiReturn(2, '请输入企业名称');
        if (!$company_id_type) apiReturn(2, '请选择企业证件类型');
        if (!$company_id_num) apiReturn(2, '请输入企业证件号');
        if (!$company_img) apiReturn(2, '请上传企业营业执照');
        //        if (!$user_name) apiReturn(2, '请输入法人姓名');
        //        if (!$user_id_type) apiReturn(2, '请选择法人证件类型');
        //        if (!$user_id_num) apiReturn(2, '请输入法人证件号');
        //        if (!$user_mobile) apiReturn(2, '请输入手机号');

        $data = [
            'user_id' => $user_id,
            'company_name' => $company_name,
            'company_id_type' => $company_id_type,
            'company_id_num' => $company_id_num,
            'company_img' => str_replace(getHost(), '', $company_img),
            'user_name' => $user_name,
            'user_id_type' => $user_id_type,
            'user_id_num' => $user_id_num,
            'user_mobile' => $user_mobile,
            'status' => 0
        ];

        $time = time();
        if ($id) {
            $data['update_time'] = $time;
            $res = Db::name('company')->where('id', $id)->update($data);
            if ($res) {
                apiReturn(1, '提交成功');
            } else {
                apiReturn(2, '提交失败');
            }
        } else {
            $data['create_time'] = $time;
            $res = Db::name('company')->insert($data);
            if ($res) {
                apiReturn(1, '提交成功');
            } else {
                apiReturn(2, '提交失败');
            }
        }
    }

    /**
     * 企业认证信息回显
     * */
    public function companyAuthInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');

        $type = array_values(array_filter(C('COMPANY_CART_TYPE')));

        $info = Db::name('company')->where('user_id', $user_id)->find();
        if ($info) {
            $info['company_img'] = getPicture($info['company_img']);
            $type_index = array_search($info['company_id_type'], $type);
            $info['type_index'] = $type_index !== -1 ? $type_index : 0;
        }

        $data = [
            'info' => $info ? : [],
            'type' => $type,
            'type_index' => $info['type_index'] ? : 0
        ];

        apiReturn(1, '获取数据成功', $data);
    }

    /**
     * 银行卡提现回显信息
     * */
    public function bankWithdrawInfo()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');

        $info = Db::name('user')->where('id', $user_id)->find();
        $info['withdraw_type'] = C('WITHDRAW_TYPE') ? : 1;

        apiReturn(1, '获取数据成功', $info);
    }

    /**
     * 银行卡提现
     * */
    public function bankWithdraw()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $user_name = $input['user_name'];
        $card_num = $input['card_num'];
        $bank_name = $input['bank_name'];
        $profit = $input['profit'];

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');
        if (!$user_name) apiReturn(2, '请输入账户名');
        if (!$card_num) apiReturn(2, '请输入账户');
        if (!$bank_name) apiReturn(2, '请输入开户行');
        if (!$profit) apiReturn(2, '请输入提现金额');

        $user_info = Db::name('user')->where('id', $user_id)->find();
        if (!$user_info) apiReturn(3, '用户不存在');

        if ($user_info['profit'] < $profit) apiReturn(2, '提现金额不能大于账户余额');

        Db::startTrans();
        try {
            $user_data = [
                'profit' => $user_info['profit'] - $profit,
                'bank_user_name' => $user_name,
                'bank_card_num' => $card_num,
                'bank_name' => $bank_name,
                'update_time' => time()
            ];
            $res = Db::name('user')->where('id', $user_id)->update($user_data);
            if (!$res) {
                Db::rollback();
                apiReturn(2, '提现失败');
            }

            $withdraw_data = [
                'user_id' => $user_id,
                'profit' => $profit,
                'user_name' => $user_name,
                'card_num' => $card_num,
                'bank_name' => $bank_name,
                'create_time' => time()
            ];
            $withdraw_id = Db::name('withdraw')->insertGetId($withdraw_data);

            $profit_data = [
                'user_id' => $user_id,
                'profit' => $profit,
                'before' => $user_info['profit'],
                'after' => $user_info['profit'] - $profit,
                'type' => 1,
                'remark' => '银行卡提现',
                'link_id' => $withdraw_id,
                'link_table' => 'withdraw',
                'create_time' => time()
            ];
            Db::name('profit_log')->insert($profit_data);

            Db::commit();
            apiReturn(1, '提现成功');
        } catch (\Throwable $e) {
            Db::rollback();
            apiReturn(2, '提现失败');
        }
    }

    /**
     * 微信提现
     * */
    public function wechatWithdraw()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $profit = $input['profit'];

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');
        if (!$profit) apiReturn(2, '请输入提现金额');

        if (empty($user_info['openid'])) apiReturn(2, 'openid缺失');

        $order_sn = uniqid();          //订单号

        Db::startTrans();
        try {
            $user_data = [
                'profit' => $user_info['profit'] - $profit,
                'update_time' => time()
            ];
            $res = Db::name('user')->where('id', $user_id)->update($user_data);
            if (!$res) {
                Db::rollback();
                apiReturn(2, '提现失败');
            }

            $withdraw_data = [
                'order_sn' => $order_sn,
                'user_id' => $user_id,
                'profit' => $profit,
                'status' => 2,
                'pay_time' => time(),
                'create_time' => time()
            ];
            $withdraw_id = Db::name('withdraw')->insertGetId($withdraw_data);

            $profit_data = [
                'user_id' => $user_id,
                'profit' => $profit,
                'before' => $user_info['profit'],
                'after' => $user_info['profit'] - $profit,
                'type' => 2,
                'remark' => '微信提现',
                'link_id' => $withdraw_id,
                'link_table' => 'withdraw',
                'create_time' => time()
            ];
            Db::name('profit_log')->insert($profit_data);

            $obj = new wxPay();
            $res = $obj->transfers($user_info['openid'], $profit, $order_sn);
            if (!$res) {
                Db::rollback();
                apiReturn(1, '提现失败');
            }

            Db::commit();
            apiReturn(1, '提现成功');
        } catch (\Throwable $e) {
            Db::rollback();
            apiReturn(2, '提现失败');
        }

    }

    /**
     * 服务购买
     * */
    public function servicePay()
    {
        $input = Request()->param();

        $id = $input['id'];
        $user_id = $input['user_id'];

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');
        if (!$id) apiReturn(2, '服务ID不存在');

        $info = Db::name('service')->where('id', $id)->find();
        if (empty($info)) apiReturn(2, '服务不存在');

        $user_info = Db::name('user')->where('id', $user_id)->find();
        if (empty($user_info)) apiReturn(3, '用户不存在');
        if ($user_info['is_auth'] == 0) apiReturn(4, '请先进行企业认证');

        Db::startTrans();
        try {
            $time = time();
            $order_sn = createOrderSn($user_id);
            $pay_price = $info['price'];

            // 生成待支付订单
            $order_data = [
                'user_id' => $user_id,
                'service_id' => $id,
                'service_name' => $info['name'],
                'order_sn' => $order_sn,
                'all_price' => $pay_price,
                'pay_price' => $pay_price,
                'create_time' => $time
            ];
            Db::name('order')->insert($order_data);

            $obj = new wxPay();
            //调用示例（最后两个参数为可选参数）
            $pay_data = $obj->jsApi($user_info['openid'], $pay_price, $order_sn, '服务购买', getHost() . '/Index/Notify/notice');
            if ($pay_data) {
                $data = [
                    'order_sn' => $order_sn,
                    'pay_data' => $pay_data
                ];
                Db::commit();
                apiReturn(1, '获取支付信息成功', $data);
            } else {
                Db::rollback();
                apiReturn(2, '购买失败');
            }
        } catch (\Throwable $e) {
            Db::rollback();
            apiReturn(2, '购买失败' . $e->getMessage());
        }
    }

    /**
     * 待支付订单支付
     * */
    public function orderPay()
    {
        $input = Request()->param();

        $id = $input['id'];
        $user_id = $input['user_id'];

        if (!$user_id) apiReturn(3, '您还未登录，请先登录');
        if (!$id) apiReturn(2, '订单ID不存在');

        $info = Db::name('order')->where('id', $id)->find();
        if (empty($info)) apiReturn(2, '订单不存在');

        if ($info['status'] != 1 || $info['user_id'] != $user_id) apiReturn(2, '订单状态异常');

        $user_info = Db::name('user')->where('id', $user_id)->find();
        if (empty($user_info)) apiReturn(3, '用户不存在');

        $obj = new wxPay();
        //调用示例（最后两个参数为可选参数）
        $info['pay_price'] = 0.01;

        $order_sn = createOrderSn($user_id);
        $res = Db::name('order')->where('id', $id)->setField('order_sn', $order_sn);
        if (!$res) apiReturn(2, '支付失败');

        $pay_data = $obj->jsApi($user_info['openid'], $info['pay_price'], $order_sn, '服务购买', getHost() . '/Index/Notify/notice');

        if ($pay_data) {
            $data = [
                'order_sn' => $info['order_sn'],
                'pay_data' => $pay_data
            ];
            apiReturn(1, '获取支付信息成功', $data);
        } else {
            apiReturn(2, '支付失败');
        }
    }

    public function test()
    {
        try {
            $redis = new Redis();
            $redis->connect('127.0.0.1', 6379);
            $redis->auth('123456'); // 添加密码验证
            echo "Redis 连接成功！";
        } catch (\Exception $e) {
            echo "Redis 连接失败：" . $e->getMessage();
        }

        Queue::later(15, 'app\index\job\DelayTask', ['param1' => 'value1']);
    }

    /**
     * 订单列表
     * */
    public function orderList()
    {
        $input = Request()->param();

        $user_id = $input['user_id'];
        $status = $input['status'];
        $page = isset($input['page']) ? $input['page'] : 1;
        $pagesize = isset($input['pagesize']) ? $input['pagesize'] : 1;


        if (!$user_id) apiReturn(3, '您还未登录，请先登录');

        $where['is_del'] = 0;
        $where['user_id'] = $user_id;

        if ($status) $where['status'] = $status;

        $list = Db::name('order')->where($where)->order('id desc')->page($page, $pagesize)->select();
        if ($list) {
            foreach ($list as &$v) {
                switch ($v['status']) {
                    case 1:
                        $class = 'wzf';
                        $desc_text = '待支付';
                        break;
                    case 2:
                        $class = 'yzf';
                        $desc_text = '已开通';
                        break;
                    case 3:
                        $class = 'ygq';
                        $desc_text = '已过期';
                        break;
                }
                $v['class'] = $class;
                $v['desc_text'] = $desc_text;


                $v['expire_time'] = timeFormat($v['expire_time'], 'Y-m-d');
            }
            apiReturn(1, '获取数据成功', $list);
        } else {
            apiReturn(2, '暂无更多数据');
        }
    }

}


